﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace LogManagement
{
    public class Log4netHelper
    {
        public static void LogInfo(Log4netType Log4netType, string FunctionName, string Message, System.Exception e = null)
        {
            string Type = GetDescription(typeof(Log4netType), Log4netType);
            switch (Log4netType)
            {
                case Log4netType.Error:
                    LogManager.GetLogger(Type).Error(FunctionName, Message, e);
                    break;

                case Log4netType.Info:
                    LogManager.GetLogger(Type).Info(FunctionName, Message, e);
                    break;

                case Log4netType.Trace:
                    LogManager.GetLogger(Type).Debug(FunctionName, Message, e);
                    break;
            }
        }

        /// <summary>
        /// 返回指定枚举类型的指定值的描述
        /// </summary>
        /// <param name="t">枚举类型</param>
        /// <param name="v">枚举值</param>
        /// <returns></returns>
        private static string GetDescription(Type t, object v)
        {
            try
            {
                FieldInfo oFieldInfo = t.GetField(GetName(t, v));
                var attributes =
                    (DescriptionAttribute[])oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return (attributes.Length > 0) ? attributes[0].Description : GetName(t, v);
            }
            catch
            {
                return string.Empty;
            }
        }

        private static string GetName(Type t, object v)
        {
            try
            {
                return Enum.GetName(t, v);
            }
            catch
            {
                return "UNKNOWN";
            }
        }
    }
}